import 'dart:async';
import 'dart:io';

import 'package:country_code_picker/country_code_picker.dart';
import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/helper/enums.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/helper/text_styler.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/images.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_text_field.dart';
import 'package:efood_multivendor/view/screens/auth/widget/code_picker_widget.dart';
import 'package:efood_multivendor/view/screens/auth/widget/guest_button.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:otp_text_field/otp_field.dart';
import 'package:pinput/pinput.dart';
import 'package:timer_button/timer_button.dart';

class SignInScreen extends StatefulWidget {
  final bool exitFromApp;
  SignInScreen({required this.exitFromApp});

  @override
  _SignInScreenState createState() => _SignInScreenState();
}

class _SignInScreenState extends State<SignInScreen> {
  final FocusNode _phoneFocus = FocusNode();
  final FocusNode _passwordFocus = FocusNode();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final OtpFieldController _otpController = OtpFieldController();
  String? _countryDialCode;
  bool _canExit = GetPlatform.isWeb ? true : false;
  @override
  void initState() {
    super.initState();
    _countryDialCode =
        Get.find<AuthController>().getUserCountryCode().isNotEmpty
            ? Get.find<AuthController>().getUserCountryCode()
            : CountryCode.fromCountryCode(
                    Get.find<SplashController>().configModel?.country ?? 'ET')
                .dialCode;
    _phoneController.text = Get.find<AuthController>().getUserNumber();
    _passwordController.text = Get.find<AuthController>().getUserPassword();
    Get.find<AuthController>().stopLoading();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(onWillPop: () async {
      if (widget.exitFromApp) {
        if (Get.find<AuthController>().isWaitingForOTP) {
          Get.find<AuthController>().waitForOTP(false);
          return Future.value(false);
        } else {
          if (_canExit) {
            if (GetPlatform.isAndroid) {
              SystemNavigator.pop();
            } else if (GetPlatform.isIOS) {
              exit(0);
            } else {
              Navigator.pushNamed(
                  context, RouteHelper.getInitialRoute("SplashScreen"));
            }
            return Future.value(false);
          } else {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
              content: Text('back_press_again_to_exit'.tr,
                  style: TextStyle(color: Colors.white)),
              behavior: SnackBarBehavior.floating,
              backgroundColor: Colors.green,
              duration: Duration(seconds: 2),
              margin: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
            ));
            _canExit = true;
            Timer(Duration(seconds: 2), () {
              _canExit = false;
            });
            return Future.value(false);
          }
        }
      } else {
        return true;
      }
    }, child: GetBuilder<AuthController>(builder: (authController) {
      TextStyle selectedStyle = sfBold.copyWith(
          fontSize: MediaQuery.of(context).size.height * 0.02,
          color: Theme.of(context).primaryColor);
      TextStyle nonSelectedStyle = sfRegular.copyWith(
        fontSize: 12,
        color: Color.fromARGB(255, 9, 5, 28),
      );
      return Scaffold(
        appBar: !widget.exitFromApp && !authController.isWaitingForOTP
            ? AppBar(
                leading: IconButton(
                  onPressed: () {
                    authController.back();
                    Get.back();
                  },
                  icon: Icon(Icons.arrow_back_ios_rounded,
                      color: Theme.of(context).textTheme.bodyMedium?.color),
                ),
                elevation: 0,
                backgroundColor: Colors.transparent)
            : null,
        body: SafeArea(
          child: Scrollbar(
            child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
              child: Container(
                height: 90.h,
                width: context.width > 700 ? 700 : context.width,
                padding: context.width > 700
                    ? EdgeInsets.all(Dimensions.PADDING_SIZE_DEFAULT)
                    : null,
                decoration: context.width > 700
                    ? BoxDecoration(
                        color: Theme.of(context).cardColor,
                        borderRadius:
                            BorderRadius.circular(Dimensions.RADIUS_SMALL),
                        boxShadow: [
                          BoxShadow(
                              color: Colors.grey[Get.isDarkMode ? 700 : 300]!,
                              blurRadius: 5,
                              spreadRadius: 1)
                        ],
                      )
                    : null,
                child: GetBuilder<AuthController>(builder: (authController) {
                  return !authController.isWaitingForOTP
                      ? Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                              Stack(
                                children: [
                                  Image.asset(Images.illustration, width: 50.h),
                                  Positioned(
                                      bottom: 1.h,
                                      child: Padding(
                                        padding: EdgeInsets.only(left: 8.0),
                                        child: Text(
                                          "enter_your_phone_number".tr,
                                          style: sfRegular.copyWith(
                                              fontSize: 3.h,
                                              fontWeight: FontWeight.w600,
                                              color: Colors.grey[900]),
                                        ),
                                      ))
                                ],
                              ),
                              SizedBox(
                                  height: Dimensions.PADDING_SIZE_EXTRA_LARGE),
                              Container(
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(
                                      Dimensions.RADIUS_SMALL),
                                  color: Theme.of(context).cardColor,
                                  boxShadow: [
                                    BoxShadow(
                                        color: Colors
                                            .grey[Get.isDarkMode ? 800 : 200]!,
                                        spreadRadius: 1,
                                        blurRadius: 5)
                                  ],
                                ),
                                child: Column(children: [
                                  Row(children: [
                                    CodePickerWidget(
                                      alignLeft: true,
                                      onChanged: (CountryCode countryCode) {
                                        setState(() {
                                          _countryDialCode =
                                              countryCode.dialCode;
                                        });
                                      },
                                      initialSelection:
                                          Get.find<SplashController>()
                                              .configModel
                                              ?.country,
                                      favorite: [_countryDialCode ?? ''],
                                      flagDecoration:
                                          BoxDecoration(shape: BoxShape.circle),
                                      showCountryOnly: true,
                                      padding: EdgeInsets.zero,
                                      showDropDownButton: true,
                                      backgroundColor: Colors.white,
                                      flagWidth: 50,
                                      hideMainText: true,
                                      textStyle: sfRegular.copyWith(
                                        fontSize: Dimensions.fontSizeLarge,
                                        color: Theme.of(context)
                                            .textTheme
                                            .bodyMedium
                                            ?.color,
                                      ),
                                    ),
                                    Center(
                                      child: Text(
                                        _countryDialCode ?? '',
                                        style: sfRegular,
                                      ),
                                    ),
                                    Expanded(
                                        flex: 10,
                                        child: CustomTextField(
                                          hintText: 'phone'.tr,
                                          controller: _phoneController,
                                          focusNode: _phoneFocus,
                                          nextFocus: _passwordFocus,
                                          inputType: TextInputType.phone,
                                          divider: false,
                                        )),
                                    Padding(
                                        padding: EdgeInsets.all(8.0),
                                        child: GestureDetector(
                                            onTap: () {
                                              authController.fetchOTPChannel(
                                                  _countryDialCode ?? '',
                                                  _phoneController.text.trim());
                                            },
                                            child: Container(
                                                height: 6.h,
                                                width: 6.h,
                                                decoration: BoxDecoration(
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            2.w),
                                                    gradient: LinearGradient(
                                                        colors: [
                                                          Theme.of(context)
                                                              .primaryColor,
                                                          Theme.of(context)
                                                              .colorScheme
                                                              .secondary
                                                        ])),
                                                child: !authController.isLoading
                                                    ? Icon(
                                                        Icons.arrow_forward,
                                                        color: Colors.white,
                                                        size: 3.h,
                                                      )
                                                    : Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                .all(8.0),
                                                        child:
                                                            CircularProgressIndicator
                                                                .adaptive(
                                                          valueColor:
                                                              AlwaysStoppedAnimation(
                                                                  Colors.white),
                                                        ),
                                                      ))))
                                  ]),
                                ]),
                              ),
                              SizedBox(
                                height: 3.h,
                              ),
                              Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: getStyledText(
                                    Get.find<SplashController>()
                                            .configModel
                                            ?.loginTip ??
                                        '',
                                    '9533',
                                    selectedStyle,
                                    nonSelectedStyle),
                              ),
                              Spacer(),
                              GuestButton(),
                            ])
                      : Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                GestureDetector(
                                  onTap: () => authController.waitForOTP(false),
                                  child: Container(
                                    width: 12.w,
                                    height: 12.w,
                                    decoration: BoxDecoration(
                                        borderRadius:
                                            BorderRadius.circular(1.5.h),
                                        color: Theme.of(context)
                                            .primaryColor
                                            .withOpacity(0.3)),
                                    child: Icon(
                                      Icons.arrow_back,
                                      color: Theme.of(context).primaryColor,
                                    ),
                                  ),
                                ),
                                SizedBox(height: 5.h),
                                Text(
                                  "Enter the \ncode from the SMS",
                                  maxLines: 2,
                                  style: sfRegular.copyWith(
                                      fontSize: 30,
                                      color: Color.fromARGB(255, 9, 5, 28)),
                                ),
                                SizedBox(height: 3.h),
                                Text(
                                  "We sent a code to $_countryDialCode ${_phoneController.text}. Please enter the code below to verify your phone number.",
                                  style: sfRegular.copyWith(fontSize: 16),
                                ),
                                SizedBox(height: 3.h),
                                Container(
                                  padding: EdgeInsets.all(1.w),
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius:
                                          BorderRadius.circular(1.5.h),
                                      boxShadow: [
                                        BoxShadow(
                                            color:
                                                Colors.grey.withOpacity(0.12),
                                            spreadRadius: 7,
                                            blurRadius: 5)
                                      ]),
                                  child: Pinput(
                                    autofocus: true,
                                    length: 6,
                                    onCompleted: (pin) => (authController
                                                .otpChannel.isNotEmpty &&
                                            authController.otpChannel ==
                                                OtpChannel.firebase.name)
                                        ? authController.verifyOTP(
                                            pin, _phoneController.text)
                                        : authController.verifyOTPWithOption(
                                            pin, _phoneController.text),
                                  ),
                                ),
                                SizedBox(height: 3.h),
                                Align(
                                    alignment: Alignment.center,
                                    child: TimerButton(
                                      label: "Send OTP Again",
                                      buttonType: ButtonType.textButton,
                                      timeOutInSeconds: 80,
                                      onPressed: () {
                                        authController.fetchOTPChannel(
                                            _countryDialCode ?? '',
                                            _phoneController.text.trim());
                                      },
                                      disabledColor: Colors.transparent,
                                      color: Colors.transparent,
                                      disabledTextStyle: const TextStyle(
                                          fontSize: 16.0, color: Colors.black),
                                      activeTextStyle: TextStyle(
                                          fontSize: 16.0,
                                          color: Theme.of(context)
                                              .colorScheme
                                              .secondary),
                                    )),
                                Spacer(),
                                SizedBox(height: 20.h),
                                Container(
                                  height: 7.h,
                                  width: 90.w,
                                  decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.circular(1.5.h),
                                      gradient: LinearGradient(
                                          begin: Alignment.topLeft,
                                          end: Alignment.bottomRight,
                                          colors: [
                                            Theme.of(context).primaryColor,
                                            Theme.of(context)
                                                .colorScheme
                                                .secondary
                                          ])),
                                  child: Center(
                                    child: !authController.isLoading
                                        ? Text("Next",
                                            style: sfBold.copyWith(
                                                fontSize: 18,
                                                color: Colors.white))
                                        : CircularProgressIndicator.adaptive(
                                            valueColor: AlwaysStoppedAnimation(
                                                Colors.white),
                                          ),
                                  ),
                                ),
                              ]),
                        );
                }),
              ),
            ),
          ),
        ),
      );
    }));
  }
}
